#!/usr/bin/env bash

set -o errexit
set -o pipefail 


# Enter your VPN login details here so you won't be asked.
VPN_USER=""
VPN_PASS=""

# Check if file is provided
if [ -z "$1" ]; then
    echo "Usage: $0 /path/to/yourfile.ovpn"
    exit 1
fi

OVPN_FILE=$1

# Check if the file exists
if [ ! -f "$OVPN_FILE" ]; then
    echo "File not found!"
    exit 1
fi

# Extract the base name of the file without extension
CONN_NAME=$(basename "$OVPN_FILE" .ovpn)

# Check if the connection already exists
if nmcli connection show | grep -q "$CONN_NAME"; then

    echo "Connection $CONN_NAME already exists. Delete it?"
    echo "y -> yes | n -> no | c -> connect"
    read -p "[y/n/c] > " yn
    case $yn in
        y)  echo "Connection $CONN_NAME is deleted."
            nmcli connection delete $CONN_NAME 
            exit 0                           
        ;;
        n) exit 0
        ;;
        c)  if nmcli connection show --active | grep -q "$CONN_NAME"; then
                echo "Connection $CONN_NAME is already active."
                exit 0
            else
                nmcli connection up "$CONN_NAME"
                echo "VPN connection $CONN_NAME has been successfully connected."
            fi
        ;;
    esac

else

    # Import the .ovpn file
    nmcli connection import type openvpn file "$OVPN_FILE"

    # Set username and password
    if [ -z "$VPN_USER" ]; then
        read -p "Enter VPN username: " VPN_USER
    fi
    if [ -z "$VPN_PASS" ]; then
        read -sp "Enter VPN password: " VPN_PASS
    fi

    # Make the connection available for all users
    nmcli connection modify "$CONN_NAME" connection.permissions ''

    # Modify the connection with the username
    sudo nmcli connection modify "$CONN_NAME" +vpn.data username="$VPN_USER"

    # Create a secrets file for the password
    SECRETS_FILE="/etc/NetworkManager/system-connections/$CONN_NAME.nmconnection"
    sudo sed -i "s;\[ipv4\];\[vpn-secrets\]\npassword=$VPN_PASS\n\n\[ipv4\];g" $SECRETS_FILE
    sudo sed -i "s;password-flags=1;password-flags=0;g" $SECRETS_FILE

    # Ensure that sed modified $SECRETS_FILE
    if ! sudo grep -oq "$VPN_PASS" "$SECRETS_FILE"; then
        if ! sudo grep -oq "password-flags=0" "$SECRETS_FILE"; then
        exit 1
        fi
    fi

    # Ensure the file has the correct permissions
    sudo chmod 600 "$SECRETS_FILE"

    # Restart NetworkManager to apply changes
    sudo systemctl restart NetworkManager

    # Connect to the VPN
    nmcli connection up "$CONN_NAME"

    echo "VPN connection $CONN_NAME has been successfully configured and connected."

fi